package com.ruyuan.seckilling.render.async.listener;

import com.alibaba.fastjson.JSON;
import com.ruyuan.seckilling.render.async.BaseRenderPageListener;
import com.ruyuan.seckilling.render.async.PageRenderContext;
import com.ruyuan.seckilling.render.async.event.Event01LoadPageConfig;
import com.ruyuan.seckilling.render.entity.PageConfig;
import com.ruyuan.seckilling.render.service.PageConfigService;
import com.ruyuan.starter.async.anno.Channel;
import com.ruyuan.starter.async.event.BaseEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.ruyuan.seckilling.common.ChannelKey.CHANNEL_01_LOAD_PAGE_CONFIG;
import static com.ruyuan.seckilling.common.ChannelKey.CHANNEL_02_DOWNLOAD_TEMPLATE_FILE;
import static com.ruyuan.seckilling.render.async.PageRenderEventHolder.EVENT_02;

/**
 * @author zhonghuashishan
 */
@Slf4j
@Component
@Channel(CHANNEL_01_LOAD_PAGE_CONFIG)
public class Event01Listener extends BaseRenderPageListener<Event01LoadPageConfig> {

    @Autowired
    private PageConfigService pageConfigService;

    @Override
    public boolean accept(BaseEvent event) {
        return event instanceof Event01LoadPageConfig;
    }

    /**
     * 1、查询页面信息
     */
    @Override
    protected void doThisStep(Event01LoadPageConfig event, PageRenderContext context) {
        String pageCode = context.getPageCode();

        Runnable task = () -> {
            PageConfig pageConfig = pageConfigService.queryByPageCode(pageCode);
            if (pageConfig == null) {
                context.getPageLog().setSuccess(false);
                context.getPageLog().setInfo("page不存在");
                context.setShouldSkip(true);
                return;
            }
            context.setPageConfig(pageConfig);
            context.getPageLog().setTemplateId(pageConfig.getTemplateId());
            bossEventBus.publish(CHANNEL_02_DOWNLOAD_TEMPLATE_FILE, EVENT_02, context);
            log.info("第1步，查询页面配置信息, pageConfig={}", JSON.toJSONString(pageConfig, true));
        };

        executorService.execute(CHANNEL_01_LOAD_PAGE_CONFIG, task);
    }
}